import Vue from "vue";
import Router from "vue-router";
import Login from "../components/Login";
import Main from "@/components/comm/Main";
import NewsTypeList from "@/components/news/NewsTypeList";
import MemberList from "@/components/member/MemberList";
import store from "@/components/store/index";
import UserList from "@/components/user/UserList";
import MenuList from "@/components/menu/MenuList";
import BannerItem from "@/components/banner/BannerItem";

Vue.use(Router);

const router = new Router({
  mode: "hash",
  routes: [
    //默认首页.
    {
      path: "/",
      redirect: "login",
    },
    //登录
    {
      path: "/login",
      name: "Login",
      component: Login,
    },
    //main主页面
    {
      path: "/main",
      name: "Main",
      component: Main,
      children: [
        {
          path: "news-type-list",
          name: "NewsTypeList",
          component: NewsTypeList,
        },
        {
          path: "member-list",
          name: "MemberList",
          component: MemberList,
        },
        {
          path: "userlist",
          name: "UserList",
          component: UserList,
        },
        {
          path: "menulist",
          name: "MenuList",
          component: MenuList,
        },
        {
          path: "banneritem",
          name: "BannerItem",
          component: BannerItem,
        },
      ],
    },
  ],
});

// 增加前置守卫
//to 即将进入的目标路由对象
//next是一个函数,放行,如果next函数中没有参数,直接去from目标地址,如果有参数去函数中的地址
router.beforeEach((to, from, next) => {
  //let isLogin = localStorage.getItem("isLogin");
  console.log("to.path", to.path);
  if (to.path === "/login") {
    //login路由不管是否登录都放行
    next();
  } else {
    let isLogin = store.state.userStore.isLogin;
    //判断是否登录
    if (!isLogin) {
      Vue.prototype.$message.error("没有登录,请先登录");
      next({ path: "/login" });
    } else {
      next();
    }
  }
});

// 全局后置守卫
//router.afterEach((to, from) => {
//在离开某个组件(页面)去新的组件(页面)之前可以在这里做什么事情
//  console.log(`路由${from.path}切换${to.path}完成`);
//});

export default router;
